package com.example.lending.View.Adapter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;

import com.example.lending.Model.Book;
import com.example.lending.Model.Borrow;
import com.example.lending.Model.User;
import com.example.lending.R;
import com.example.lending.ViewModel.BookViewModel;
import com.example.lending.ViewModel.BorrowViewModel;
import com.example.lending.ViewModel.UserViewModel;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class TypeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>  {
    private Context context;
    private List<Book> books;
    private BorrowViewModel borrowViewModel;
    private BookViewModel bookViewModel;
    private UserViewModel userViewModel;
    //private LifecycleOwner owner;
    private List<User> users;
    public TypeAdapter(Context context, List<Book> books,BorrowViewModel borrowViewModel,BookViewModel bookViewModel,UserViewModel userViewModel,List<User>users) {
        this.context = context;
        this.books = books;
        this.borrowViewModel=borrowViewModel;
        this.bookViewModel=bookViewModel;
        this.userViewModel=userViewModel;
        this.users=users;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_onlion_book,parent,false);
        return new CommenViewHolder(view);
    }
    public static String getLoadTime(int time) {//将数字根据大小不同存放为不同的形式
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
        if (time < 1000)
            return time + "次";
        else if (time < 1000000)
            return df.format((float)time/1000) + "千次";
        else if (time < 100000000)
            return df.format((float)time/1000000) + "百万次";
        else
            return  df.format((float)time/100000000)+ "亿次";

    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position) {

        if(holder instanceof CommenViewHolder){
            final Book book = books.get(position);
            ((CommenViewHolder) holder).mTitle.setText(book.getName());
            ((CommenViewHolder) holder).mReviewNumber.setText(book.getStar_number()+"");
            ((CommenViewHolder) holder).mPlayNumber.setText(getLoadTime(book.getLook_number()));
            ((CommenViewHolder) holder).mCover.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Uri uri=Uri.parse("https://baike.baidu.com/item/"+((CommenViewHolder) holder).mTitle.getText());
                    Intent intent =new Intent(Intent.ACTION_VIEW);
                    intent.setData(uri);
                    holder.itemView.getContext().startActivity(intent);
                }
            });
            ((CommenViewHolder) holder).button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String username=context.getSharedPreferences("user", Context.MODE_PRIVATE).getString("username","");
                    books.get(position).setNumber(1);
                    books.get(position).setUser(username);//将用户的名字放进book中
                    //bookViewModel.insertBooks(book);
                    //bookViewModel.deleteBooks(books.get(position));
                    bookViewModel.updataBooks(books.get(position));

                    Borrow borrow=new Borrow();
                    borrow.setName(book.getName());
                    borrow.setDuration(7);
                    SimpleDateFormat formatter=new   SimpleDateFormat   ("HH:mm:ss");
                    Date curDate=new Date(System.currentTimeMillis());//获取当前时间
                    String str= formatter.format(curDate);

                    borrow.setTime(str);
                    borrow.setUserid(username);
                    borrowViewModel.insertBorrows(borrow);
                    int x=0;
                    //List<User>users=userViewModel.getAllUserLive().getValue();
                    for(int i=0;i<users.size();i++){
                        if(users.get(i).getName().equals(username)){
                            System.out.println("ppppppppppp");
                            users.get(i).setMoney(users.get(i).getMoney()-Integer.parseInt(book.getPrice()));
                            userViewModel.updataUsers(users.get(i));
                            x=1;
                        }
                    }
                    if(x==1)
                        Toast.makeText(context, "借阅成功", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        if(books==null)
            return 0;
        return books.size();
    }

    class CommenViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        ImageView mCover;
        TextView mTitle,mPlayNumber,mReviewNumber;
        Button button;

        public CommenViewHolder(@NonNull View itemView) {
            super(itemView);
            mCover=itemView.findViewById(R.id.item_img);
            mTitle=itemView.findViewById(R.id.item_title);
            mPlayNumber=itemView.findViewById(R.id.item_player);
            mReviewNumber=itemView.findViewById(R.id.item_review);
            mCover.setOnClickListener(this);
            mReviewNumber.setOnClickListener(this);
            button=itemView.findViewById(R.id.btn_get);
        }

        @Override
        public void onClick(View v) {
            int position=getLayoutPosition();
            System.out.println("position--"+position);

        }
    }
}
